package com.raos.example.redisexample;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.raos.example.redisexample.constants.BloomFilterCache;
import com.raos.example.redisexample.constants.RedisKeyConstants;
import com.raos.example.redisexample.dal.model.City;
import com.raos.example.redisexample.service.ICityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 布隆过滤器数据加载应用程序运行器
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2021/7/22 22:01
 */
@Slf4j
@Component
public class BloomFilterDataLoadApplicationRunner implements ApplicationRunner {

    @Autowired
    ICityService cityService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("=========begin load city data to Redis for BloomFilter===========");
        List<City> cities = cityService.list();
        BloomFilter<String> bloomFilter =
                BloomFilter.create(Funnels.stringFunnel(StandardCharsets.UTF_8), 100000000, 0.03);
        cities.parallelStream().forEach(city -> {
                bloomFilter.put(RedisKeyConstants.CITY_KEY + ":" + city.getId());
        });
        BloomFilterCache.cityBloom = bloomFilter;
        log.info("=========finish load city data to Redis for BloomFilter===========");
    }

}
